import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import iconv from 'iconv-lite';
import * as qs from 'qs';

@Injectable()
export class AxiosService {
  constructor(private readonly httpService: HttpService) {}

  /**
   * 获取ip地址信息
   * @param ip
   * @returns
   */
  async getIpAddress(ip: string) {
    try {
      const IP_URL = 'https://whois.pconline.com.cn/ipJson.jsp';
      const response = await this.httpService.axiosRef(`${IP_URL}?ip=${ip}&json=true`, {
        responseType: 'arraybuffer',
        transformResponse: [
          function (data) {
            const str = iconv.decode(data, 'gbk');
            return JSON.parse(str);
          },
        ],
      });
      return response.data.addr;
    } catch (error) {
      return '未知';
    }
  }

  async post<T>(url, data) {
    const result = await this.httpService.axiosRef.post<T>(url, data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    return result;
  }

  async get<T = any>(url: string, query?: Record<string, any>): Promise<T> {
    const [link, paramsString = ''] = url.split('?');
    const params = qs.parse(paramsString);
    query = { ...params, ...query, output: 'json' };
    const queryString = qs.stringify(query);
    url = `${link}?${queryString}`;

    const result = await this.httpService.axiosRef.get<T>(url, {
      // 添加 responseType 配置
      responseType: 'json',
    });
    return result.data;
  }
}
